package org.optimus.phaselistener;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletResponse;

import org.optimus.utils.FacesUtils;

public class LoginPhaseListener implements PhaseListener {

	@Override
	public void afterPhase(PhaseEvent co) {
		FacesContext facesContext = co.getFacesContext();
		HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", -1);
		
		String[] paginasPerminitidas = {"principal"};
		FacesContext fc = co.getFacesContext();
		String paginaActual = fc.getViewRoot().getViewId();
		NavigationHandler nh = fc.getApplication().getNavigationHandler();
		
		boolean paginaLogin = paginaActual.lastIndexOf("login") > -1 ? true : false;
		
		if (paginaActual != null) {
			boolean permitido = false;
			for (String pagina : paginasPerminitidas) {
				permitido = paginaActual.lastIndexOf(pagina) > -1 ? true : false;
				
				if (permitido) {
					break;
				}
			}
			
			if (!estaLogueado() && !paginaLogin) {
				System.out.println(" pretty : login ::" + " !paginaLogin " + !paginaLogin + " :: !estaLogueado() :: "+ !estaLogueado());
				nh.handleNavigation(fc, null, "pretty:login");
			}
 
		}


	}

	@Override
	public void beforePhase(PhaseEvent co) {
		// TODO Auto-generated method stub

	}

	@Override
	public PhaseId getPhaseId() {
		// TODO Auto-generated method stub
		return null;
	}
	
	private boolean estaLogueado(){
		return FacesUtils.existeUsuarioLogueado();
	}

}
